package cn.wen233.srpc.core.service.factory;

import cn.wen233.srpc.basic.model.ServerConfig;
import cn.wen233.srpc.core.service.SunglowReferenceInvocationHandler;

import java.lang.reflect.Proxy;

/**
 * 代理工厂
 *
 * @author wenei
 * @date 2021-10-27 19:38
 */
public class ReferenceProxyFactory {

    /**
     * 没有指定相关Host和Port信息，无法找到服务端
     *
     * @see cn.wen233.srpc.core.service.factory.ReferenceProxyFactory#getProxyService(java.lang.Class, cn.wen233.srpc.basic.model.ServerConfig, java.lang.Class)
     */
    @Deprecated
    public static <T> T getProxyService(Class<T> interfaceClass) {
        Object proxy = Proxy.newProxyInstance(
                Thread.currentThread().getContextClassLoader(),
                new Class[]{interfaceClass},
                new SunglowReferenceInvocationHandler()
        );
        if (interfaceClass.isInstance(proxy)) {
            return (T) proxy;
        }
        return null;
    }

    public static <T> T getProxyService(Class<T> interfaceClass, ServerConfig config, Class<?> fallback) {
        Object proxy = Proxy.newProxyInstance(
                Thread.currentThread().getContextClassLoader(),
                new Class[]{interfaceClass},
                new SunglowReferenceInvocationHandler(config, fallback)
        );
        if (interfaceClass.isInstance(proxy)) {
            return (T) proxy;
        }
        return null;
    }
}
